package bean.dao;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import Entities.Cliente;
import Entities.Sucursal;

public class ClienteDAO extends HibernateDAO{
	private static ClienteDAO instancia;
	private static SessionFactory sf;
	
	public static ClienteDAO getInstancia(){
		if(instancia == null){
			sf = (HibernateDAO.getInstancia().getSession().getSessionFactory());
			instancia = new ClienteDAO();
		} 
		return instancia;
	}
	
	public boolean altaCliente(Cliente c)
	{
		
		System.out.println("Voy a persistir en DAOOOOOOOOOOOO AHHHHHHHHHHHHH!!!!");
		
		boolean bandera;
		Session s = HibernateDAO.getInstancia().getSession();
		Transaction t = s.beginTransaction();
		bandera = s.save(c) != null;
		t.commit();
		return bandera;
	}
	
		
	public void bajaCliente(int id)
	{
		Session s = HibernateDAO.getInstancia().getSession();
		Transaction t = s.beginTransaction();
		Query buscarCliente =  s.createQuery("SELECT c FROM Cliente c WHERE c.Id = :id").setParameter("id",id);
		Cliente cli = (Cliente) buscarCliente.uniqueResult();
        //Borro el objeto de persistencia
        s.delete(cli);
        t.commit();
	}
	
	public void actualizarCliente(Cliente c)
	{
		Session s = HibernateDAO.getInstancia().getSession();
		Transaction t = s.beginTransaction();
		//c.setId(c.getId());
		s.update(c);
		t.commit();
	}
	
	@SuppressWarnings("unchecked")
	public List<Cliente> getClientes(){
		Session s = HibernateDAO.getInstancia().getSession();
		Transaction t = s.beginTransaction();
		List<Cliente> lista = s.createQuery("from Cliente").list();		
		t.commit();
		return lista;
	}
	
	public Cliente getCliente(String doc){
		Session s = HibernateDAO.getInstancia().getSession();
		Transaction t = s.beginTransaction();
		Cliente c = (Cliente) s.createQuery(" from Cliente where documento = :identificador").setString("identificador", doc).uniqueResult();;		
		t.commit();
		return c;
	}

	public static void setSf(SessionFactory sf) {
		ClienteDAO.sf = sf;
	}

	public static SessionFactory getSf() {
		return sf;
	}

	

}
